const WebSocket = require('ws');
const axios = require('axios');
const PORT = 8088;
const wss = new WebSocket.Server({ port: PORT });

console.log(`WebSocket server is running on ws://localhost:${PORT}`);

wss.on('connection', (ws) => {
    ws.on('message', (message) => {
        let msgStr;
        if (Buffer.isBuffer(message)) {
            msgStr = message.toString();
        } else {
            msgStr = String(message);
        }
        console.log('Received message:', msgStr);
        let askData = {
            "messages": [{ "role": "user", "content": msgStr }],
            "model": "deepseek-coder:6.7b",
            "options": {}
      
          }
        // 发送请求
        axios.post("http://127.0.0.1:11434/api/chat", askData, {
        }).then(data => {
            // console.log('data.data---->',data.data);
            const arrayString = '[' + data.data.trim().replace(/}\s*{/g, '},{') + ']';
            let jsonArray;
            try {
                jsonArray = JSON.parse(arrayString);
                jsonArray.forEach(element => {
                    console.log('---->',element.message.content);
                    ws.send(element.message.content)
                });
            } catch (e) {
                console.error("解析 JSON 失败", e);
                return "";
            }
            // console.log('jsonArray---->',jsonArray);
       

        })
    });
});

